package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.dishDao;
import com.example.domain.Dish;
import com.example.domain.DishFlavor;
import com.example.dto.DishDto;
import com.example.service.DishFlavorService;
import com.example.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class DishServiceImpl extends ServiceImpl<dishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {

        this.save(dishDto);

        Long id = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map(flavor->{
            flavor.setDishId(id);
            return flavor;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getDishDtoWithFlavor(Long id) {

        Dish byId = this.getById(id);

        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(byId, dishDto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<DishFlavor>();

        wrapper.eq(DishFlavor::getDishId, id);

        List<DishFlavor> list = dishFlavorService.list(wrapper);

        dishDto.setFlavors(list);

        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {

        this.updateById(dishDto);

        Long id = dishDto.getId();

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<DishFlavor>();

        wrapper.eq(id!=null,DishFlavor::getDishId, id);

        dishFlavorService.remove(wrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map(flavor->{
            flavor.setDishId(id);
            return flavor;
        }).collect(Collectors.toList());


        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public void deleteWithFlavor(Long id) {

            this.removeById(id);

            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<DishFlavor>();

            wrapper.eq(DishFlavor::getDishId, id);

            dishFlavorService.remove(wrapper);

    }

    @Override
    public void changeStatus(Long id, Integer status) {

        Dish byId = this.getById(id);

        byId.setStatus(status);

        this.updateById(byId);

    }
}
